package com.tarena.lbs.basic.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.basic.web.repository.TagLibraryRepository;
import com.tarena.lbs.basic.web.repository.UserRepository;
import com.tarena.lbs.basic.web.repository.UserTagsRepository;
import com.tarena.lbs.basic.web.utils.AuthenticationContextUtils;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.basic.param.UserTagsParam;
import com.tarena.lbs.pojo.basic.po.TagLibraryPO;
import com.tarena.lbs.pojo.basic.po.UserPO;
import com.tarena.lbs.pojo.basic.po.UserTagsPO;
import com.tarena.lbs.pojo.basic.vo.TagLibraryVO;
import com.tarena.lbs.pojo.basic.vo.TagVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TagService {
    //对应表格lbs_tag_library
    @Autowired
    private TagLibraryRepository tagLibraryRepository;
    @Autowired
    private UserTagsRepository userTagsRepository;
    @Autowired
    private UserRepository userRepository;
    public Map<String, List<TagVO>> tagMap(Integer tagType) {
        //1.使用tagType 查询某一个类型的标签所有的列表 select * from lbs_tag_library where tag_type=0
        QueryWrapper<TagLibraryPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tag_type",tagType);
        List<TagLibraryPO> pos = tagLibraryRepository.list(queryWrapper);
        //查询出来不分级别的 poList
        //2.Map返回值所需要的数据全部都在poList 用业务封装转化一下数据
        Map<String,List<TagVO>> mapVO=assembleTagMap(pos);
        return mapVO;
    }

    private Map<String, List<TagVO>> assembleTagMap(List<TagLibraryPO> pos) {
        //1.map需要key 根据key值 封装list
        Map<String,List<TagVO>> mapVO=new HashMap<>();
        //2.遍历pos 筛选pos 先把一级标签筛选出来
        List<TagLibraryPO> firstLevelPos = pos.stream().filter(po -> po.getTagParentId().equals(0)).collect(Collectors.toList());
        //3.循环一级标签
        for (TagLibraryPO firstLevelPo : firstLevelPos) {
            //拿到一级标签名字
            String tagName=firstLevelPo.getTagName();
            //拿到一级标签id
            Integer tagId=firstLevelPo.getId();
            //使用一级标签的id对pos做筛选 拿到该一级标签的下级po列表
            List<TagLibraryPO> secondLevelPos = pos.stream().filter(po -> po.getTagParentId().equals(tagId)).collect(Collectors.toList());
            //使用po的二级标签集合转化TagVo集合
            List<TagVO> vos=
                    secondLevelPos.stream().map(po-> {
                                TagVO vo=new TagVO();
                                vo.setTagCategoryName(tagName);
                                TagLibraryVO tagLibraryVO=new TagLibraryVO();
                                BeanUtils.copyProperties(po,tagLibraryVO);
                                vo.setTagLibraryBO(tagLibraryVO);
                                return vo;
                            }
                    ).collect(Collectors.toList());
            mapVO.put(tagName,vos);
        }
        return mapVO;
    }

    public void bindUserTags(UserTagsParam param) throws BusinessException {
        //1.获取用户id
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        Integer userId=userPrinciple.getId();
        //先将该用户所关联的所有标签绑定全部清空
        //delete from lbs_user_tags where user_id=#{}
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        userTagsRepository.remove(queryWrapper);
        //每次提交的数据 都需要封装LiSt<UserTagsPO>
        //ServiceImpl支持对表格的批量写操作
        //2.从param 拿到tagIds=[1,2,3,4,5,6]
        List<UserTagsPO> pos=null;
        String[] tagIds = param.getTagIds().split(",");
        pos= Arrays.stream(tagIds).map(tagId->{
            UserTagsPO po=new UserTagsPO();
            po.setUserId(userId);
            po.setTagId(Integer.parseInt(tagId));
            return po;
        }).collect(Collectors.toList());
        //insert into lbs_user_tags (id,user_id,tag_id) values (元素1),(元素2),...
        userTagsRepository.saveBatch(pos);//批量写入,pos有多少元素,一次新增多少元素
        //为了避免批量新增的时候 数据量太大,导致执行时间过长.也支持 分批批量
        //userTagsRepository.saveBatch(pos,50);
        //3.更新用户的状态 update lbs_user set status=1 where id=#{}
        //userRepository.update().set("status",1).eq("id",userId);
        UserPO poParam=new UserPO();
        poParam.setStatus(1);
        poParam.setId(userId);
        userRepository.updateById(poParam);
    }
}
